package cn.itsource.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import cn.itsource.basic.config.exception.BusinessException;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.LoginInfoUtil;
import cn.itsource.basic.util.RedisService;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.pojo.dto.LoginDto;
import cn.itsource.org.pojo.info.LoginInfo;
import cn.itsource.org.pojo.vo.LoginVo;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee,EmployeeQuery> implements IEmployeeService {

    //基础方法由继承得到

    /**
     * 注入mapper
     */
    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * RedisService
     */
    @Autowired
    private RedisService redisService;

    @Override
    public List<Employee> findManager() {
        return employeeMapper.findManager();
    }

    @Override
    public AjaxResult login(LoginDto loginDto) {

        //-----------------登录业务------------------
        //1.根据用户名查询employee对象,如果没查到返回 jd:账户名与密码不匹配，请重新输入
        Employee dbEmployee = employeeMapper.selectByUsername(loginDto);
        Optional.ofNullable(dbEmployee).orElseThrow(() -> new BusinessException("账户名与密码不匹配，请重新输入"));
        //2.比对密码
        //2.1对页面传递过来的密码进行加盐加密,再和数据库加密串进行比对
        //                                    数据库的老盐                                    页面传递的密码
        String pagePwd = MD5.create().setSalt(dbEmployee.getSalt().getBytes()).digestHex(loginDto.getPassword());

        //2.2比对失败,返回错误
        if (!StringUtils.equals(pagePwd,dbEmployee.getPassword())){
            throw  new BusinessException("账户名与密码不匹配，请重新输入");
        }

        //3.把数据存到redis里面 30分钟  key:token(uuid) value:用户信息
        String token = IdUtil.fastSimpleUUID();

        //拷贝对象
        LoginInfo loginInfo = BeanUtil.copyProperties(dbEmployee, LoginInfo.class);
        LoginVo loginVo = BeanUtil.copyProperties(dbEmployee, LoginVo.class);
        loginVo.setToken(token);

        redisService.setStringKeyAndValue(token,loginInfo,30);

        //token一定要给前端    还有头像 用户其他信息
        return AjaxResult.createSuccess(loginVo);
    }

    @Override
    public List<Employee> findShopAllEmployee() {
        Long shopId = LoginInfoUtil.getShopId();
        return employeeMapper.findShopAllEmployee(shopId);
    }

}